<!doctype html>




<html class="theme-next pisces" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>



<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
    
  
  <link href="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  
    
      
    

    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.lug.ustc.edu.cn/css?family=Monda:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






  

<link href="//cdn.staticfile.org/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.0" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Web,JavaScript," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.0" />






<meta name="description" content="HTML5 脚本编程媒体元素Flash毒瘤，不得不用。而HTML5 新增了&amp;lt;audio&amp;gt;和&amp;lt;video&amp;gt;，为了摆脱毒瘤。它们都提供了用于实现常用功能的JavaScript API，允许为媒体创建自定义的控件。&amp;lt;video src=&amp;quot;conference.mpg&amp;quot; id=&amp;quot;myVideo&amp;quot;&amp;gt;Video player not">
<meta property="og:type" content="article">
<meta property="og:title" content="《 JavaScript 高级程序设计》备忘-第十六章-2">
<meta property="og:url" content="http://codingme.xyz/2016/10/30/javascript-note-16-2/index.html">
<meta property="og:site_name" content="CodingMe">
<meta property="og:description" content="HTML5 脚本编程媒体元素Flash毒瘤，不得不用。而HTML5 新增了&amp;lt;audio&amp;gt;和&amp;lt;video&amp;gt;，为了摆脱毒瘤。它们都提供了用于实现常用功能的JavaScript API，允许为媒体创建自定义的控件。&amp;lt;video src=&amp;quot;conference.mpg&amp;quot; id=&amp;quot;myVideo&amp;quot;&amp;gt;Video player not">
<meta property="og:updated_time" content="2016-11-02T06:35:01.302Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="《 JavaScript 高级程序设计》备忘-第十六章-2">
<meta name="twitter:description" content="HTML5 脚本编程媒体元素Flash毒瘤，不得不用。而HTML5 新增了&amp;lt;audio&amp;gt;和&amp;lt;video&amp;gt;，为了摆脱毒瘤。它们都提供了用于实现常用功能的JavaScript API，允许为媒体创建自定义的控件。&amp;lt;video src=&amp;quot;conference.mpg&amp;quot; id=&amp;quot;myVideo&amp;quot;&amp;gt;Video player not">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"right","display":"post"},
    fancybox: true,
    motion: false,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://codingme.xyz/2016/10/30/javascript-note-16-2/"/>





  <title> 《 JavaScript 高级程序设计》备忘-第十六章-2 | CodingMe </title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  










  
  
    
  

  <div class="container one-collumn sidebar-position-right page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">CodingMe</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle"></p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
  <link itemprop="mainEntityOfPage" href="http://codingme.xyz/2016/10/30/javascript-note-16-2/">

  <span style="display:none" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <meta itemprop="name" content="Huang SJ">
    <meta itemprop="description" content="">
    <meta itemprop="image" content="/uploads/avatar.jpg">
  </span>

  <span style="display:none" itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
    <meta itemprop="name" content="CodingMe">
    <span style="display:none" itemprop="logo" itemscope itemtype="http://schema.org/ImageObject">
      <img style="display:none;" itemprop="url image" alt="CodingMe" src="">
    </span>
  </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                《 JavaScript 高级程序设计》备忘-第十六章-2
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">
            

            

            
          </span>

          

          
            
          

          

          
          

          

          

        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="HTML5-脚本编程"><a href="#HTML5-脚本编程" class="headerlink" title="HTML5 脚本编程"></a>HTML5 脚本编程</h1><h2 id="媒体元素"><a href="#媒体元素" class="headerlink" title="媒体元素"></a>媒体元素</h2><p>Flash毒瘤，不得不用。而HTML5 新增了<code>&lt;audio&gt;</code>和<code>&lt;video&gt;</code>，为了摆脱毒瘤。<br>它们都提供了用于实现常用功能的JavaScript API，允许为媒体创建自定义的控件。<br><code>&lt;video src=&quot;conference.mpg&quot; id=&quot;myVideo&quot;&gt;Video player not available.&lt;/video&gt;</code></p>
<p>必需:src 属性，指向要加载的媒体文件。<br>可选:width和height 属性以指定视频播放器的大小，<br>可选:poster 属性指定图像的URI 可以在加载视频内容期间显示一幅图像。<br>可选:controls 属性，则意味着浏览器应该显示UI 控件，以便用户直接操作媒体。<br>标签之间的任何内容都将作为后备内容，在浏览器不支持这两个媒体元素的情况下显示。</p>
<p>因为并非所有浏览器都支持所有媒体格式，所以可以指定多个不同的媒体来源。利用<code>&lt;source&gt;</code>标签。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div></pre></td><td class="code"><pre><div class="line"><span class="comment">&lt;!-- 嵌入视频 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">video</span> <span class="attr">id</span>=<span class="string">"myVideo"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">source</span> <span class="attr">src</span>=<span class="string">"conference.webm"</span> <span class="attr">type</span>=<span class="string">"video/webm; codecs='vp8, vorbis'"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">source</span> <span class="attr">src</span>=<span class="string">"conference.ogv"</span> <span class="attr">type</span>=<span class="string">"video/ogg; codecs='theora, vorbis'"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">source</span> <span class="attr">src</span>=<span class="string">"conference.mpg"</span>&gt;</span></div><div class="line">Video player not available.</div><div class="line"><span class="tag">&lt;/<span class="name">video</span>&gt;</span></div><div class="line"><span class="comment">&lt;!-- 嵌入音频 --&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">audio</span> <span class="attr">id</span>=<span class="string">"myAudio"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">source</span> <span class="attr">src</span>=<span class="string">"song.ogg"</span> <span class="attr">type</span>=<span class="string">"audio/ogg"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">source</span> <span class="attr">src</span>=<span class="string">"song.mp3"</span> <span class="attr">type</span>=<span class="string">"audio/mpeg"</span>&gt;</span></div><div class="line">Audio player not available.</div><div class="line"><span class="tag">&lt;/<span class="name">audio</span>&gt;</span></div></pre></td></tr></table></figure>
<a id="more"></a>
<p>支持这两个媒体元素的浏览器有IE9+、Firefox 3.5+、Safari 4+、Opera 10.5+、Chrome、iOS 版Safari 和Android 版WebKit。</p>
<h3 id="属性"><a href="#属性" class="headerlink" title="属性"></a>属性</h3><p>autoplay、buffered、bufferedBytes、bufferingRate、bufferingThrottled、totalBytes、seekable、playbackRate等等。</p>
<h3 id="事件"><a href="#事件" class="headerlink" title="事件"></a>事件</h3><p>两个标签能够触发的事件。</p>
<p>abort、canplay等等。<br>这些事件之所以如此具体，就是为了让开发人员只使用少量HTML 和JavaScript（与创建Flash 影片相比）即可编写出自定义的音频/视频播放器。</p>
<h3 id="自定义媒体播放器"><a href="#自定义媒体播放器" class="headerlink" title="自定义媒体播放器"></a>自定义媒体播放器</h3><p>使用<code>&lt;audio&gt;</code>和<code>&lt;video&gt;</code>元素的play()和pause()方法，可以手工控制媒体文件的播放。<br>组合使用属性、事件和这两个方法，很容易创建一个自定义的媒体播放器:</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"mediaplayer"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"video"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">video</span> <span class="attr">id</span>=<span class="string">"player"</span> <span class="attr">src</span>=<span class="string">"movie.mov"</span> <span class="attr">poster</span>=<span class="string">"mymovie.jpg"</span></span></div><div class="line"><span class="attr">width</span>=<span class="string">"300"</span> <span class="attr">height</span>=<span class="string">"200"</span>&gt;</div><div class="line">Video player not available.</div><div class="line"><span class="tag">&lt;/<span class="name">video</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"controls"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">"button"</span> <span class="attr">value</span>=<span class="string">"Play"</span> <span class="attr">id</span>=<span class="string">"video-btn"</span>&gt;</span></div><div class="line"><span class="tag">&lt;<span class="name">span</span> <span class="attr">id</span>=<span class="string">"curtime"</span>&gt;</span>0<span class="tag">&lt;/<span class="name">span</span>&gt;</span>/<span class="tag">&lt;<span class="name">span</span> <span class="attr">id</span>=<span class="string">"duration"</span>&gt;</span>0<span class="tag">&lt;/<span class="name">span</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div><div class="line"><span class="tag">&lt;/<span class="name">div</span>&gt;</span></div></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="comment">//取得元素的引用</span></div><div class="line"><span class="keyword">var</span> player = <span class="built_in">document</span>.getElementById(<span class="string">"player"</span>),</div><div class="line">btn = <span class="built_in">document</span>.getElementById(<span class="string">"video-btn"</span>),</div><div class="line">curtime = <span class="built_in">document</span>.getElementById(<span class="string">"curtime"</span>),</div><div class="line">duration = <span class="built_in">document</span>.getElementById(<span class="string">"duration"</span>);</div><div class="line"><span class="comment">//更新播放时间</span></div><div class="line">duration.innerHTML = player.duration;</div><div class="line"><span class="comment">//为按钮添加事件处理程序</span></div><div class="line">EventUtil.addHandler(btn, <span class="string">"click"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line"><span class="keyword">if</span> (player.paused)&#123;</div><div class="line">player.play();</div><div class="line">btn.value = <span class="string">"Pause"</span>;</div><div class="line">&#125; <span class="keyword">else</span> &#123;</div><div class="line">player.pause();</div><div class="line">btn.value = <span class="string">"Play"</span>;</div><div class="line">&#125;</div><div class="line">&#125;);</div><div class="line"><span class="comment">//定时更新当前时间</span></div><div class="line">setInterval(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</div><div class="line">curtime.innerHTML = player.currentTime;</div><div class="line">&#125;, <span class="number">250</span>);</div></pre></td></tr></table></figure>
<p>同样的代码也可以用于<code>&lt;audio&gt;</code>元素，以创建自定义的音频播放器。</p>
<h3 id="检测编解码器的支持情况"><a href="#检测编解码器的支持情况" class="headerlink" title="检测编解码器的支持情况"></a>检测编解码器的支持情况</h3><p>并非所有浏览器都支持<code>&lt;video&gt;</code>和<code>&lt;audio&gt;</code>的所有编解码器，而这基本上就意味着你必须提供多个媒体来源。<br>不过，也有一个JavaScript API 能够检测浏览器是否支持某种格式和编解码器。</p>
<p>这两个媒体元素都有一个canPlayType()方法，该方法接收一种格式/编解码器字符串，返回”probably”、”maybe”或””（ 空字符串）。<br>所以可以使用：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">if</span> (audio.canPlayType(<span class="string">"audio/mpeg"</span>))&#123;</div><div class="line"><span class="comment">//进一步处理</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>在给canPlayType()传入<strong>一种</strong>MIME 类型的情况下，则返回值很可能是”maybe”或空字符串；<br>媒体文件本身只不过是音频或视频的一个容器，而真正决定文件能否播放的还是编码的格式。<br>在同时传入MIME 类型和编解码器的情况下，可能性就会增加，返回的字符串会变成”probably”。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> audio = <span class="built_in">document</span>.getElementById(<span class="string">"audio-player"</span>);</div><div class="line"><span class="comment">//很可能"maybe"</span></div><div class="line"><span class="keyword">if</span> (audio.canPlayType(<span class="string">"audio/mpeg"</span>))&#123;</div><div class="line"><span class="comment">//进一步处理</span></div><div class="line">&#125;</div><div class="line"><span class="comment">//可能是"probably"</span></div><div class="line"><span class="keyword">if</span> (audio.canPlayType(<span class="string">"audio/ogg; codecs=\"vorbis\""</span>))&#123;</div><div class="line"><span class="comment">//进一步处理</span></div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>音频      字符串                                 支持的浏览器<br>AAC     audio/mp4; codecs=”mp4a.40.2”          IE9+、Safari 4+、iOS版Safari<br>MP3     audio/mpeg                             IE9+、Chrome<br>Vorbis  audio/ogg; codecs=”vorbis”             Firefox 3.5+、Chrome、Opera 10.5+<br>WAV     audio/wav; codecs=”1”                  Firefox 3.5+、Opera 10.5+、Chrome</p>
<p>视频          字符串                                         支持的浏览器<br>H.264   video/mp4; codecs=”avc1.42E01E, mp4a.40.2”      IE9+、Safari 4+、iOS版Safari、Android版WebKit<br>Theora  video/ogg; codecs=”theora”                      Firefox 3.5+、Opera 10.5、Chrome<br>WebM    video/webm; codecs=”vp8, vorbis”                Firefox 4+、Opera 10.6、Chrome</p>
<h3 id="Audio类型"><a href="#Audio类型" class="headerlink" title="Audio类型"></a>Audio类型</h3><p><code>&lt;audio&gt;</code>元素还有一个原生的JavaScript 构造函数Audio，可以在任何时候播放音频。<br>从同为DOM元素的角度看，Audio 与Image 很相似，但Audio 不用像Image 那样必须插入到文档中。<br>只要创建一个新实例，并传入音频源文件即可。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line"><span class="keyword">var</span> audio = <span class="keyword">new</span> Audio(<span class="string">"sound.mp3"</span>);</div><div class="line">EventUtil.addHandler(audio, <span class="string">"canplaythrough"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line">audio.play();</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>创建新的Audio 实例即可开始下载指定的文件。下载完成后，调用play()就可以播放音频。<br>在iOS 中，调用play()时会弹出一个对话框，得到用户的许可后才能播放声音。<br>如果想在一段音频播放后再播放另一段音频，必须在onfinish 事件处理程序中调用play()方法。<br>(思考；simonGame中有跟随音乐点击按钮的事件。其中的音乐也是各个音频文件的调用播放。<br>如果疯狂点击按钮触发play()，按照前一句话意思，会有多个play()同时触发，音乐会混杂。<br>实际使用的时候由于音效时间短，所以并不需要考虑到混杂的情况。<br>但是，<br>1.是否可以定义一个变量，通过onfinish 和 play 事件处理程序更改这个变量，来判定当前是否有音乐正在播放?<br>2.需不需要考虑GC问题？)</p>
<h2 id="历史状态管理"><a href="#历史状态管理" class="headerlink" title="历史状态管理"></a>历史状态管理</h2><p>通过haschange事件知道URL的变化;HTML5 通过更新history 对象为管理历史状态提供了方便。<br>通过状态管理API,能够在不加载新页面的情况下改变浏览器的URL。所以需要使用history.pushState()方法，<br>接收三个参数：状态对象、新状态的标题和可选的相对URL。<br><code>history.pushState({name:&quot;Nicholas&quot;}, &quot;Nicholas&#39; page&quot;, &quot;nicholas.html&quot;);</code><br>执行pushState()方法后，新的状态信息就会被加入历史状态栈，而浏览器地址栏也会变成新的相对URL。<br>但浏览器并不会真的向服务器发送请求，即使状态改变之后查询location.href 也会返回与地址栏中相同的地址。<br>第二个参数目前还没有浏览器实现，因此完全可以只传入一个空字符串，或者一个短标题也可以。<br>第一个参数应该尽可能提供初始化页面状态所需的各种信息。</p>
<p>因为pushState()会创建新的历史状态，所以“后退”按钮也能使用了。<br>按下“后退”按钮，会触发window 对象的popstate 事件。<br>popstate 事件的事件对象有一个state 属性，这个属性就包含着当初以第一个参数传递给pushState()的状态对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">EventUtil.addHandler(<span class="built_in">window</span>, <span class="string">"popstate"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</div><div class="line"><span class="keyword">var</span> state = event.state;</div><div class="line"><span class="keyword">if</span> (state)&#123; <span class="comment">//第一个页面加载时state 为空</span></div><div class="line">processState(state);</div><div class="line">&#125;</div><div class="line">&#125;);</div></pre></td></tr></table></figure>
<p>浏览器加载的第一个页面没有状态，因此单击“后退”按钮返回浏览器加载的第一个页面时，event.state 值为null。<br>要更新当前状态，可以调用replaceState()，传入的参数与pushState()的前两个参数相同。<br>调用这个方法不会在历史状态栈中创建新状态，只会重写当前状态。<br><code>history.replaceState({name:&quot;Greg&quot;}, &quot;Greg&#39;s page&quot;);</code></p>
<p>支持HTML5 历史状态管理的浏览器有Firefox 4+、Safari 5+、Opera 11.5+和Chrome。<br>在Safari 和Chrome 中，传递给pushState()或replaceState()的状态对象中不能包含DOM 元素。<br>而Firefox支持在状态对象中包含DOM 元素。<br>要确保使用pushState()创造的每一个“假”URL，在Web 服务器上都有一个真的、实际存在的URL 与之对应。<br>否则，单击“刷新”按钮会导致404 错误。</p>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>


    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Web/" rel="tag"># Web</a>
          
            <a href="/tags/JavaScript/" rel="tag"># JavaScript</a>
          
        </div>
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/10/26/javascript-note-16-1/" rel="next" title="《 JavaScript 高级程序设计》备忘-第十六章-1">
                <i class="fa fa-chevron-left"></i> 《 JavaScript 高级程序设计》备忘-第十六章-1
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/11/01/javascript-note-17-1/" rel="prev" title="《 JavaScript 高级程序设计》备忘-第十七章-1">
                《 JavaScript 高级程序设计》备忘-第十七章-1 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="Huang SJ" />
          <p class="site-author-name" itemprop="name">Huang SJ</p>
          <p class="site-description motion-element" itemprop="description"></p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">75</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              <a href="/categories">
                <span class="site-state-item-count">4</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">9</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/hsj1992" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://twitter.com/hsj9527" target="_blank" title="Twitter">
                  
                    <i class="fa fa-fw fa-twitter"></i>
                  
                  Twitter
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/u/1694147905" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://www.freecodecamp.cn/hsj1992" target="_blank" title="FreeCodeCamp">
                  
                    <i class="fa fa-fw fa-fire"></i>
                  
                  FreeCodeCamp
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://codepen.io/hsj1992/" target="_blank" title="codepen">
                  
                    <i class="fa fa-fw fa-codepen"></i>
                  
                  codepen
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://hsj1992.oschina.io/" target="_blank" title="码云镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  码云镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.coding.me/" target="_blank" title="coding镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  coding镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://hsj1992.github.io/" target="_blank" title="github镜像">
                  
                    <i class="fa fa-fw fa-code"></i>
                  
                  github镜像
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://codingme-6dd8a.firebaseapp.com" target="_blank" title="Firebase镜像">
                  
                    <i class="fa fa-fw fa-google"></i>
                  
                  Firebase镜像
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#HTML5-脚本编程"><span class="nav-number">1.</span> <span class="nav-text">HTML5 脚本编程</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#媒体元素"><span class="nav-number">1.1.</span> <span class="nav-text">媒体元素</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#属性"><span class="nav-number">1.1.1.</span> <span class="nav-text">属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#事件"><span class="nav-number">1.1.2.</span> <span class="nav-text">事件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#自定义媒体播放器"><span class="nav-number">1.1.3.</span> <span class="nav-text">自定义媒体播放器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#检测编解码器的支持情况"><span class="nav-number">1.1.4.</span> <span class="nav-text">检测编解码器的支持情况</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Audio类型"><span class="nav-number">1.1.5.</span> <span class="nav-text">Audio类型</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#历史状态管理"><span class="nav-number">1.2.</span> <span class="nav-text">历史状态管理</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Huang SJ</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery/2.1.3/jquery.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fastclick/1.0.6/fastclick.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/jquery_lazyload/1.9.7/jquery.lazyload.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/velocity/1.2.1/velocity.ui.min.js"></script>

  
  <script type="text/javascript" src="//cdn.staticfile.org/fancybox/2.1.5/jquery.fancybox.pack.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.0"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.0"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.0"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.0"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.0"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.0"></script>



  



  




	




  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
      search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();
    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';
      $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = $( "entry", xmlResponse ).map(function() {
            return {
              title: $( "title", this ).text(),
              content: $("content",this).text(),
              url: $( "url" , this).text()
            };
          }).get();
          var $input = document.getElementById(search_id);
          var $resultContent = document.getElementById(content_id);
          $input.addEventListener('input', function(){
            var matchcounts = 0;
            var str='<ul class=\"search-result-list\">';
            var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
            $resultContent.innerHTML = "";
            if (this.value.trim().length > 1) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var content_index = [];
                var data_title = data.title.trim().toLowerCase();
                var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                var data_url = decodeURIComponent(data.url);
                var index_title = -1;
                var index_content = -1;
                var first_occur = -1;
                // only match artiles with not empty titles and contents
                if(data_title != '') {
                  keywords.forEach(function(keyword, i) {
                    index_title = data_title.indexOf(keyword);
                    index_content = data_content.indexOf(keyword);
                    if( index_title >= 0 || index_content >= 0 ){
                      isMatch = true;
                      if (i == 0) {
                        first_occur = index_content;
                      }
                    }

                  });
                }
                // show search results
                if (isMatch) {
                  matchcounts += 1;
                  str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                  var content = data.content.trim().replace(/<[^>]+>/g,"");
                  if (first_occur >= 0) {
                    // cut out 100 characters
                    var start = first_occur - 20;
                    var end = first_occur + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if(start == 0){
                      end = 50;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    var match_content = content.substring(start, end);
                    // highlight all keywords
                    keywords.forEach(function(keyword){
                      var regS = new RegExp(keyword, "gi");
                      match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                    });

                    str += "<p class=\"search-result\">" + match_content +"...</p>"
                  }
                  str += "</li>";
                }
              })};
            str += "</ul>";
            if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
            if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
            $resultContent.innerHTML = str;
          });
          proceedsearch();
        }
      });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

  


</body>
</html>
